package com.interagriculture.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.interagriculture.common.PageResult;
import com.interagriculture.entity.Project;
import com.interagriculture.entity.query.ProjectQuery;
import com.interagriculture.mapper.ProjectMapper;
import com.interagriculture.service.ProjectService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Project)表服务实现类
 *
 * @author makejava
 * @since 2024-10-24 19:13:41
 */
@Service("projectService")
public class ProjectServiceImpl implements ProjectService {
    @Resource
    private ProjectMapper projectMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param projectId 主键
     * @return 实例对象
     */
    @Override
    public Project queryById(Integer projectId) {
        return this.projectMapper.queryById(projectId);
    }


    /**
     * 新增数据
     *
     * @param project 实例对象
     * @return 实例对象
     */
    @Override
    public Project insert(Project project) {
        this.projectMapper.insert(project);
        return project;
    }

    /**
     * 修改数据
     *
     * @param project 实例对象
     * @return 实例对象
     */
    @Override
    public Project update(Project project) {
        this.projectMapper.update(project);
        return this.queryById(project.getProjectId());
    }

    /**
     * 通过主键删除数据
     *
     * @param projectId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer projectId) {
        return this.projectMapper.deleteById(projectId) > 0;
    }

    /**
     * 分页查询
     * @param projectQuery
     * @return
     */
    @Override
    public PageResult findByPage(ProjectQuery projectQuery) {
        if(projectQuery!=null && projectQuery.getPageNum()!=null && projectQuery.getPageSize()!=null){
            PageHelper.startPage(projectQuery.getPageNum(),projectQuery.getPageSize());
        }
        if(projectQuery!=null && projectQuery.getOrderBy()!=null){
            PageHelper.orderBy(projectQuery.getOrderBy());
        }
        List<Project> projectList = projectMapper.selectByPage(projectQuery);
        PageInfo<Project> pages = new PageInfo<>(projectList);
        return new PageResult(pages.getTotal(),pages.getPages(),pages.getList());
    }

    @Override
    public void saveOrUpdate(Project project) {
        projectMapper.insertOrUpdate(project);
    }
}
